package com.huahan.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huahan.auth.Utils.CommonLoginUtils;
import com.huahan.auth.Utils.MapperUtils;
import com.huahan.auth.Utils.RandomValidateCodeUtil;
import com.huahan.auth.Utils.RedisHelper;
import com.huahan.auth.api.OAuth2Api;
import com.huahan.auth.domain.User;
import com.huahan.auth.exception.BusinessException;
import com.huahan.auth.security.component.HuahanUserDetail;
import com.huahan.auth.service.UserService;
import com.huahan.auth.mapper.UserMapper;
import com.mall.common.constant.*;
import com.mall.common.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* @author 13513
* @description 针对表【sys_user】的数据库操作Service实现
* @createDate 2024-04-26 14:48:41
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService, UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Override
    public HuahanUserDetail loadUserByUsername(String accountName) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(accountName)) {
            throw new BusinessException(ResultCode.ACCOUNT_IS_EMPTY);
        }
        User userDO = this.getOne(new QueryWrapper<User>().eq("username",accountName));
        if (ObjectUtils.isEmpty(userDO)) {
            throw new BusinessException(ResultCode.ACCOUNT_OR_PASSWORD_ERROR);
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList();
        grantedAuthorities.add(new SimpleGrantedAuthority("USER"));
        return new HuahanUserDetail(userDO, grantedAuthorities);
    }
    @Resource
    private CommonLoginUtils commonLoginUtils;
    @Override
    public R login(LoginInfoParam loginInfoParam) {
        // 通过 HTTP 客户端请求登录接口
        Map<String, String> params = new HashMap<>(16);
        // 登录方式
        String loginType = loginInfoParam.getLoginType();
        if (StringUtils.isEmpty(loginType)) {
            throw new BusinessException(ResultCode.LOGIN_METHOD_IS_EMPTY);
        }
        // 密码方式登录
        if (LoginTypeEnum.PASSWORD.getValue().equals(loginType)) {
//            if (StringUtils.isBlank(loginInfoParam.getVerifyCode())) {
//                throw new BusinessException("请输入验证码");
//            }
//            if(redisHelper.hasKey(RandomValidateCodeUtil.RANDOMCODEKEY+"admin"+loginInfoParam.getVerifyCode())){
//                // 删除验证码
//                redisHelper.deleteKey(RandomValidateCodeUtil.RANDOMCODEKEY+"admin"+loginInfoParam.getVerifyCode());
//            }else{
//                throw new BusinessException("请输入正确的验证码");
//            }
            String accountName = loginInfoParam.getAccountName();
            if (StringUtils.isEmpty(accountName)) {
                throw new BusinessException(ResultCode.ACCOUNT_IS_EMPTY);
            }
            String password = loginInfoParam.getPassword();
            if (StringUtils.isEmpty(password)) {
                throw new BusinessException(ResultCode.PASSWORD_IS_EMPTY);
            }
            params.put("username", accountName);
            params.put("password", password);
            params.put("grant_type", loginType);
        }
        // 短信方式登录
        if (LoginTypeEnum.SMS_CODE.getValue().equals(loginType)) {
            String phoneNumber = loginInfoParam.getPhone();
            if (StringUtils.isEmpty(phoneNumber)) {
                throw new BusinessException(ResultCode.PHONE_NUMBER_IS_EMPTY);
            }

            String smsCode = loginInfoParam.getSmsCode();
            if (StringUtils.isEmpty(smsCode)) {
                throw new BusinessException(ResultCode.SMS_CODE_IS_EMPTY);
            }
            params.put("phone", phoneNumber);
            params.put("smsCode", smsCode);
            params.put("grant_type", loginType);
        }
        Map<String, Object> authInfo = commonLoginUtils.login(params);
        User user = loadUserByUsername(loginInfoParam.getAccountName()).getUser();
        return R.ok("登录成功")
                .put("token", authInfo.get(OAuth2AccessToken.ACCESS_TOKEN))
                .put("refreshToken", authInfo.get(OAuth2AccessToken.REFRESH_TOKEN))
                .put("userName",user.getName());
    }
}




